import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;

import javax.swing.tree.DefaultMutableTreeNode;
import javax.xml.parsers.*;
import org.w3c.dom.*;
import org.xml.sax.SAXException;

/**
 * Title:  getXML.java
 * Description:  Manipulating XML files
 * Copyright:    Copyright (c) 2010
 * @author WANG Jiechao
 * @version 1.0
 * if you have any problem about XML DOM, consult http://wiki.hudong.com/wiki/gdQFRBHZmXWdaakJ0
 */

public class getXML {
	NodeList projects;
	String XMLFileName="record.xml";
	DocumentBuilder builder;
	Document doc;


	public getXML(){
		File f = new File(XMLFileName);
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        
        try {
        	
        	builder = factory.newDocumentBuilder();
        	doc = builder.parse(f);
        
        	Element root=doc.getDocumentElement();
		
        	projects=root.getChildNodes();		

        } catch (ParserConfigurationException e) {
		     e.printStackTrace();
		} catch (FileNotFoundException e) {
		     e.printStackTrace();
		} catch (SAXException e) {
		     e.printStackTrace();
		} catch (IOException e) {
		     e.printStackTrace();
		}
	 }
	
    public void createNodes(DefaultMutableTreeNode top) {
	    DefaultMutableTreeNode category = null;
	    DefaultMutableTreeNode book = null;

    	if(projects!=null){
    		for(int i=0;i<projects.getLength();i++){
    			if(projects.item(i).getNodeType()==Node.ELEMENT_NODE){
    				String projectName=projects.item(i).getAttributes().getNamedItem("name").getNodeValue();
    			    category = new DefaultMutableTreeNode(projectName);
    			    top.add(category);
    			    for(Node node=projects.item(i).getFirstChild();node!=null;node=node.getNextSibling()){
    					if(node.getNodeType()==Node.ELEMENT_NODE){
    						if(node.getNodeName().equals("file")){
    							String fileName=node.getFirstChild().getNodeValue();
    							book = new DefaultMutableTreeNode(fileName);
    							category.add(book);
    						}
    					}
    			    }
    			}
    		}
    	}
    			
	}
    
    public String getXMLFileName(){
    	return XMLFileName;
    }
    
    public Document getdoc(){
    	return doc;
    }
}
